#include <iostream>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (p == q) {
            return p;
        }
        TreeNode* node = root;
        while (node != nullptr) {
            if (p->val > node->val && q->val > node->val) {
                node = node->right;
            } else if (p->val < node->val && q->val < node->val) {
                node = node->left;
            } else {
                return node;
            }
        }
        return nullptr;
    }
};